//
//  CLSlider.swift
//  clreader
//
//  Created by colin on 2019/4/2.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

class CLSlider: UIView {
    
    /** 滑块的大小 */
    private let kSliderBtnWH:CGFloat = 19.0
    /** 间距 */
    private let kProgressMargin:CGFloat = 2.0
    /** 进度的宽度 */
    private var kProgressW:CGFloat {
        return self.frame.width - self.kProgressMargin
    }
    /** 进度的高度 */
    private let kProgressH:CGFloat = 3.0
    
    var handleTouchBegin:((_ progress_:CGFloat)->Void)?
    var handleValueChanged:((_ progress_:CGFloat)->Void)?
    var handleTouchEnded:((_ progress_:CGFloat)->Void)?
    
    /// 是否正在拖动
    var isDraging:Bool {
        return self.draging
    }
    
    /// 进度
    var progress:CGFloat = 0 {
        didSet {
            let finishValue  = self.progressBg.frame.width * self.progress
            var sliderFrame = self.progressSlider.frame
            sliderFrame.size.width = finishValue
            
            let buttonX = (self.frame.width - self.buttonSlider.frame.width) * self.progress
            var buttonFrame = self.buttonSlider.frame
            buttonFrame.origin.x = buttonX
            
            UIView.animate(withDuration: 0.1) { [weak self] in
                self?.progressSlider.frame = sliderFrame
                self?.buttonSlider.frame = buttonFrame
            }
            
            // self.lastPoint = self.sliderBtn.center;
        }
    }
    
    /// 缓冲进度
    var buffer:CGFloat = 0 {
        didSet {
            let finishValue = self.progressBg.frame.width * self.buffer
            var bufferFrame = self.progressBuffer.frame
            bufferFrame.size.width = finishValue
            self.progressBuffer.frame = bufferFrame
        }
    }
    
    /// 默认滑杆的颜色
    var maximumTrackTintColor:UIColor? {
        didSet { self.progressBg.backgroundColor = self.maximumTrackTintColor }
    }
    
    /// 滑杆进度颜色
    var minimumTrackTintColor:UIColor? {
        didSet { self.progressSlider.backgroundColor = self.minimumTrackTintColor }
    }
    
    /// 缓存进度颜色
    var bufferTrackTintColor:UIColor? {
        didSet { self.progressBuffer.backgroundColor = self.bufferTrackTintColor }
    }
    
    /// 默认滑杆的图片
    var maximumTrackImage:UIImage? {
        didSet {
            self.progressBg.image = self.maximumTrackImage
            self.maximumTrackTintColor = UIColor.clear
        }
    }
    /// 滑杆进度的图片
    var minimumTrackImage:UIImage? {
        didSet {
            self.progressSlider.image = self.minimumTrackImage
            self.minimumTrackTintColor = UIColor.clear
        }
    }
    
    /// 缓存进度的图片
    var bufferTrackImage:UIImage? {
        didSet {
            self.progressBuffer.image = self.bufferTrackImage
            self.bufferTrackTintColor = UIColor.clear
        }
    }
    
    private lazy var progressBg = UIImageView()
    private lazy var progressBuffer = UIImageView()
    private lazy var progressSlider = UIImageView()
    private lazy var buttonSlider = Button(frame: CGRect.zero)
    
    private var tapGesture:UITapGestureRecognizer?
    private var draging = false
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
        self.addSubviews()
    }
    
    /// 添加子视图
    private func addSubviews() {
        self.progressBg.backgroundColor = UIColor.gray
        self.progressBg.clipsToBounds = true
        self.progressBg.frame = CGRect(x: self.kProgressMargin, y: 0, width: 0, height: self.kProgressH)
        self.addSubview(self.progressBg)
        
        self.progressBuffer.backgroundColor = UIColor.white
        self.progressBuffer.clipsToBounds = true
        self.progressBuffer.frame = self.progressBg.frame
        self.addSubview(self.progressBuffer)
        
        self.progressSlider.backgroundColor = UIColor.red
        self.progressSlider.clipsToBounds = true
        self.progressSlider.frame = self.progressBg.frame
        self.addSubview(self.progressSlider)
        
        self.buttonSlider.addTarget(self, action: #selector(self.sliderBtnTouchBegin(_:)), for: .touchDown)
        self.buttonSlider.addTarget(self, action: #selector(self.sliderBtnTouchEnded(_:)), for: .touchCancel)
        self.buttonSlider.addTarget(self, action: #selector(self.sliderBtnTouchEnded(_:)), for: .touchUpInside)
        self.buttonSlider.addTarget(self, action: #selector(self.sliderBtnTouchEnded(_:)), for: .touchUpOutside)
        self.buttonSlider.addTarget(self, action: #selector(self.sliderBtnDragMoving(_:_:)), for: .touchDragInside)
        
        self.buttonSlider.frame = CGRect(x: 0, y: 0, width: self.kSliderBtnWH, height: self.kSliderBtnWH)
        self.addSubview(self.buttonSlider)
        self.buttonSlider.hideActivity()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let height = self.frame.height
        let width = self.frame.width
        
        self.progressBg.center     = CGPoint(x: self.progressBg.center.x, y: height / 2)
        self.progressBuffer.center = CGPoint(x: self.progressBuffer.center.x, y: height / 2)
        self.progressSlider.center = CGPoint(x: self.progressSlider.center.x, y: height / 2)
        self.buttonSlider.center = CGPoint(x: self.buttonSlider.center.x, y: height / 2)
        
        var bgFrame = self.progressBg.frame
        bgFrame.size.width = width - self.kProgressMargin * 2
        self.progressBg.frame = bgFrame
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension CLSlider {
    
    /// 滑块背景
    func setSliderBackgroundImage(image:UIImage?,state:UIControl.State) {
        self.buttonSlider.setBackgroundImage(image, for: state)
        self.buttonSlider.sizeToFit()
    }
    
    /// 滑块图片
    func setSliderThumbImage(image:UIImage?,state:UIControl.State) {
        self.buttonSlider.setImage(image, for: state)
        self.buttonSlider.sizeToFit()
    }
    
    func showProgress() {
        self.buttonSlider.showActivity()
    }
    
    func hideProgress() {
        self.buttonSlider.hideActivity()
    }
}

extension CLSlider {
    
    @objc private func sliderBtnTouchBegin(_ sender:Any) {
        self.draging = true
        self.handleTouchBegin?(self.progress)
    }
    
    @objc private func sliderBtnTouchEnded(_ sender:Any) {
        self.draging = false
        self.handleTouchEnded?(self.progress)
    }
    
    @objc private func sliderBtnDragMoving(_ sender:UIButton,_ event:UIEvent?) {
        // 点击的位置
        if let point = event?.allTouches?.first?.location(in: self) {
            // 获取进度值 由于btn是从 0-(self.width - btn.width)
            var progress_ = (point.x - sender.frame.width / 2) / (self.frame.width - sender.frame.width)
            progress_ = progress_ >= 1.0 ? 1.0 : progress_ <= 0.0 ? 0.0 : progress_;
            self.progress = progress_
            self.handleValueChanged?(self.progress)
        }
    }
}

extension CLSlider {
    class Button: UIButton {
        
        private lazy var indicatorView = UIActivityIndicatorView(style: .gray)
        
        func showActivity() {
            self.indicatorView.isHidden = false
            self.indicatorView.startAnimating()
        }
        
        func hideActivity() {
            self.indicatorView.isHidden = true
            self.indicatorView.stopAnimating()
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.indicatorView.hidesWhenStopped = false
            self.indicatorView.isUserInteractionEnabled = false
            self.indicatorView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
            self.indicatorView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
            self.addSubview(self.indicatorView)
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            self.indicatorView.center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
            self.indicatorView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
        }
        
        // MARK: - 将按钮的点击范围扩大
        override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
            var bounds = self.bounds
            // 扩大点击区域
            bounds =  bounds.insetBy(dx: -20.0, dy: -20.0)
            // 若点击的点在新的bounds里面。就返回yes
            return bounds.contains(point);
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
    }
}
